<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Room;
use App\Models\User;
use App\Models\Menu;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;

class RoomController extends Controller
{
    /**
     * 显示房间管理页面
     */
    public function index(Request $request): View
    {
        $perPage = 20;
        $query = Room::with(['creator', 'members', 'orders', 'menu']);

        // 搜索功能
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // 状态筛选
        if ($request->filled('status')) {
            $status = $request->get('status');
            $query->where('status', $status);
        }

        // 类型筛选
        if ($request->filled('type')) {
            $type = $request->get('type');
            $query->where('type', $type);
        }

        // 获取房间并计算统计数据
        $rooms = $query->orderBy('created_at', 'desc')->paginate($perPage);
        
        // 为每个房间添加统计数据
        $rooms->getCollection()->transform(function ($room) {
            $room->members_count = $room->members->count();
            $room->orders_count = $room->orders->count();
            return $room;
        });

        return view('admin.rooms.index', compact('rooms'));
    }

    /**
     * 显示创建房间页面
     */
    public function create(): View
    {
        $users = User::where('is_active', true)->get();
        $menus = Menu::where('is_public', true)->get();
        
        return view('admin.rooms.create', compact('users', 'menus'));
    }

    /**
     * 保存新房间
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'room_id' => 'required|string|max:50|unique:rooms,room_id',
            'title' => 'required|string|max:100',
            'description' => 'nullable|string',
            'type' => 'required|in:temporary,permanent',
            'creator_id' => 'required|exists:users,id',
            'menu_source' => 'required|in:default,custom',
            'menu_id' => 'nullable|exists:menus,id',
            'max_participants' => 'nullable|integer|min:1|max:100',
            'expires_at' => 'nullable|date|after:now',
        ]);

        $roomData = $request->only([
            'room_id', 'title', 'description', 'type', 'creator_id', 
            'menu_source', 'menu_id', 'max_participants', 'expires_at'
        ]);

        $roomData['status'] = 'active';
        $roomData['current_round'] = 1;
        $roomData['total_orders'] = 0;
        $roomData['last_activity_at'] = now();

        $room = Room::create($roomData);

        return redirect()->route('admin.rooms.show', $room)
            ->with('success', '房间创建成功！');
    }

    /**
     * 显示房间详情页面
     */
    public function show(int $id): View
    {
        $room = Room::with(['creator', 'members', 'orders', 'menu'])->findOrFail($id);
        
        // 计算统计数据
        $room->members_count = $room->members->count();
        $room->orders_count = $room->orders->count();
        
        return view('admin.rooms.show', compact('room'));
    }

    /**
     * 显示编辑房间页面
     */
    public function edit(int $id): View
    {
        $room = Room::findOrFail($id);
        $users = User::where('is_active', true)->get();
        $menus = Menu::where('is_public', true)->get();
        
        return view('admin.rooms.edit', compact('room', 'users', 'menus'));
    }

    /**
     * 更新房间
     */
    public function update(Request $request, int $id): RedirectResponse
    {
        $room = Room::findOrFail($id);
        
        $request->validate([
            'room_id' => 'required|string|max:50|unique:rooms,room_id,' . $id,
            'title' => 'required|string|max:100',
            'description' => 'nullable|string',
            'type' => 'required|in:temporary,permanent',
            'creator_id' => 'required|exists:users,id',
            'menu_source' => 'required|in:default,custom',
            'menu_id' => 'nullable|exists:menus,id',
            'max_participants' => 'nullable|integer|min:1|max:100',
            'expires_at' => 'nullable|date|after:now',
            'status' => 'required|in:active,closed,expired',
        ]);

        $roomData = $request->only([
            'room_id', 'title', 'description', 'type', 'creator_id', 
            'menu_source', 'menu_id', 'max_participants', 'expires_at', 'status'
        ]);

        $room->update($roomData);

        return redirect()->route('admin.rooms.show', $room)
            ->with('success', '房间更新成功！');
    }

    /**
     * 删除房间
     */
    public function destroy(int $id): RedirectResponse
    {
        $room = Room::findOrFail($id);
        
        // 检查是否有关联的订单
        if ($room->orders()->count() > 0) {
            return redirect()->back()
                ->with('error', '该房间有关联的订单，无法删除！');
        }

        $room->delete();

        return redirect()->route('admin.rooms.index')
            ->with('success', '房间删除成功！');
    }

    /**
     * 切换房间状态
     */
    public function toggleStatus(int $id): RedirectResponse
    {
        $room = Room::findOrFail($id);
        $room->status = $room->status === 'active' ? 'closed' : 'active';
        $room->save();

        $status = $room->status === 'active' ? '启用' : '关闭';
        return redirect()->back()->with('success', "房间 {$room->title} 已{$status}");
    }

    /**
     * 获取房间列表API
     */
    public function list(Request $request): JsonResponse
    {
        $perPage = $request->get('per_page', 20);
        $query = Room::with(['creator', 'members', 'orders', 'menu']);

        // 搜索功能
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // 状态筛选
        if ($request->filled('status')) {
            $status = $request->get('status');
            $query->where('status', $status);
        }

        // 类型筛选
        if ($request->filled('type')) {
            $type = $request->get('type');
            $query->where('type', $type);
        }

        $rooms = $query->orderBy('created_at', 'desc')->paginate($perPage);
        
        // 为每个房间添加统计数据
        $rooms->getCollection()->transform(function ($room) {
            $room->members_count = $room->members->count();
            $room->orders_count = $room->orders->count();
            return $room;
        });

        return response()->json([
            'data' => $rooms->items(),
            'pagination' => [
                'current_page' => $rooms->currentPage(),
                'last_page' => $rooms->lastPage(),
                'per_page' => $rooms->perPage(),
                'total' => $rooms->total(),
            ]
        ]);
    }

    /**
     * 获取房间详情API
     */
    public function showApi(int $id): JsonResponse
    {
        $room = Room::with(['creator', 'members', 'orders'])->findOrFail($id);
        
        // 计算统计数据
        $room->members_count = $room->members->count();
        $room->orders_count = $room->orders->count();
        
        return response()->json(['data' => $room]);
    }

    /**
     * 获取房间统计API
     */
    public function stats(): JsonResponse
    {
        $stats = [
            'total_rooms' => Room::count(),
            'active_rooms' => Room::where('status', 'active')->count(),
            'inactive_rooms' => Room::where('status', 'inactive')->count(),
            'expired_rooms' => Room::where('status', 'expired')->count(),
            'permanent_rooms' => Room::where('type', 'permanent')->count(),
            'temporary_rooms' => Room::where('type', 'temporary')->count(),
            'today_rooms' => Room::whereDate('created_at', today())->count(),
        ];

        return response()->json(['data' => $stats]);
    }
}
